﻿package com.mutouren.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;

public class RequestFilter implements Filter {

	private static Logger runLogger = LogManager.getLogger(LogAlias.SystemRun.name());
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        
        //request.setCharacterEncoding("utf-8");
    
        // 记录请求
        runLogger.debug(req.getRequestURI());
        
		// 清除缓存
        clearCache(res);
        // 登录检查
        //checkLogin(req, res);
        
        // 权限检查
        if(!checkPermission(req, res)) {
        	res.getWriter().write("you can't visit the function");       
        	return;
        }
              
        chain.doFilter(request, response);
	}
	
	private void clearCache(HttpServletResponse response) {
		response.setHeader("Pragma","No-cache"); 
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);  
	}
	
/*	private void checkLogin(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();		
		if(session.getAttribute("user") != null) return;
		
		String actionName = request.getRequestURI().replace(request.getContextPath(),"");				
		if(("/").equals(actionName) || ("/frame/login.action").equals(actionName)) return;
		
		try {
			response.sendRedirect(request.getContextPath() + "/frame/login.action");
		} catch (IOException e) {
			throw ExceptionManager.doUnChecked(e);
		}
	}*/
	
	/** 基于action的简单权限处理
	 * @param request
	 * @param response
	 * @return
	 */
	private boolean checkPermission(HttpServletRequest request, HttpServletResponse response) {		
		return true;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		runLogger.info("RequestFilter init event");
	}
	
}